<?php
namespace App\Http\Logic;

use App\Models\SwtMarketChains;
use App\Models\SwtNetwork;
use App\Models\SwtNetworkChain;
use App\Models\SwtTradeAccount;
use App\Models\SwtTradeAddress;
use App\Models\SwtUserChain;
use Illuminate\Support\Facades\DB;

class ChainLogic extends BaseLogic
{
    /**
     * @notes 添加用户链
     * @param string $chainIds
     * @param string $user_id
     * @return bool
     * @author Evil丿
     * @date 2025/04/14 14:06
     */
    public static function addUserChain(string $instId, string $instType, string $user_id) : bool
    {
        $info = SwtUserChain::where('inst_id', $instId) -> where('type', $instType) -> where('user_id', $user_id) -> first();

        if($info) {
            $info  -> delete();
            return true;
        }

        SwtUserChain::create([
            "user_id"    => $user_id,
            "inst_id"    => $instId,
            "type"       => $instType
        ]);

        return true;
    }

    /**
     * @notes 查询用户链
     * @param string $user_id
     * @return array
     * @author Evil丿
     * @date 2025/04/14 14:07
     */
    public static function queryUserChain(string $type, string $user_id, string $search = "") : array
    {
        $where = [
          ['user_id','=', $user_id]
        ];

        if($type !== "ALL") {
            $where[] = ['type','=', $type];
        }

        if($search) {
            $where[] = ['inst_id','like','%'.$search.'%'];
        }

        $inst_ids = SwtUserChain::where($where) -> pluck('inst_id');

        $chains = SwtMarketChains::whereIn('inst_id', $inst_ids) -> where('state', 'live') -> orderBy('inst_id');

        $list = $chains -> get() -> map(function ($item) {
            $item -> icon = config('app.url').'/storage'.$item -> icon;
            $item -> instId = $item -> inst_id;
            return $item;
        });

        return $list -> toArray();
    }

    /**
     * @notes 查询自选详情
     * @param string $inst_id
     * @param string $user_id
     * @return bool|array
     * @author Evil丿
     * @date 2025/04/17 11:04
     */
    public static function queryUserChainInfo(string $inst_id, string $user_id) : bool|array
    {
        $where = [
            ['user_id','=', $user_id],
            ['inst_id','=',$inst_id]
        ];

        $list = SwtUserChain::where($where) -> first();

        if(!$list) {
            self::$error = __('coin-type.not_found');
            return false;
        }

        return $list -> toArray();
    }

    /**
     * @notes 获取全部可用币
     * @param string $search
     * @return array
     * @author Evil丿
     * @date 2025/04/21 17:46
     */
    public static function getAllCoins(string $search = "") : array
    {
        $where = [
            ['quote_ccy','=','USD'],
            ['state','=','live'],
        ];

        if($search) {
            $where[] = ["base_ccy",'like','%'.$search.'%'];
        }

        $list = SwtMarketChains::where($where)
            -> select('id','base_ccy','icon','status','full_name',DB::raw('UPPER(SUBSTR(base_ccy, 1, 1)) as first_letter'))
            -> orderBy('base_ccy')
            -> get()
            -> toArray();

        $use_hot =  SwtMarketChains::where($where)
            -> select('id','base_ccy','icon','status','full_name')
            -> orderBy('base_ccy')
            -> where('status', 1)
            -> get()
            -> toArray();

        foreach($use_hot as &$v) {
            $v['icon'] = config('app.url').'/storage'.$v['icon'];
        }

        $coins = [
            'hot' => $use_hot,
            'list' => []
        ];

        foreach($list as $coin) {
            $coin['icon'] = config('app.url').'/storage'.$coin['icon'];

            $coins['list'][$coin['first_letter']][] = $coin;
        }

        return $coins;
    }

    /**
     * @notes 获取可用网络
     * @param int $coin_id
     * @return array
     * @author Evil丿
     * @date 2025/04/22 15:03
     */
    public static function getCoinChains(int $coin_id)  : array
    {
        $network_id = SwtNetworkChain::where('chain_id', $coin_id) -> pluck('network_id');

        $list = SwtNetwork::whereIn('id', $network_id) -> orderBy('status','desc') -> get() -> toArray();

        foreach($list as &$v) {
            $v['icon'] = config('app.url').'/storage'.$v['icon'];
        }

        return $list;
    }

    /**
     * @notes 获取充币页信息
     * @param int $user_id
     * @param int $coin_id
     * @param int $network_id
     * @return array
     * @author Evil丿
     * @date 2025/04/22 16:05
     */
    public static function getRechargeInfo(int $user_id, int $coin_id, int $network_id) : bool|array
    {
        $coin_info = SwtMarketChains::where('id', $coin_id) -> first();

        if($coin_info -> status == 0) {
            self::$error = __('coin-type.coin_disable');
            return false;
        }

        $network_info = SwtNetwork::where('id', $network_id) -> first();

        if($network_info -> status == 0) {
            self::$error = __('coin-type.network_disable');
            return false;
        }

        $account_id = SwtTradeAccount::where('user_id', $user_id) -> where('type',1) -> value('id');

        if(!$account_id) {
            self::$error = __('coin-type.account_not_found');
            return false;
        }

        $address_info = SwtTradeAddress::where('account_id', $account_id) -> where('network_name', $network_info -> name) -> first();

        if(!$address_info) {
            self::$error = __('coin-type.address_not_found');
            return false;
        }

        $data = [
            "coin_name"            => $coin_info -> base_ccy,
            "network_name"         => $network_info -> network_name,
            "icon"                 => config('app.url') . '/storage' . $network_info -> icon,
            "min_deposit"          => (float) $network_info -> min_deposit,
            "address"              => $address_info -> address,
            "total"                => (float) $address_info -> total,
            "fee"                  => (float) $network_info -> fee,
            "account_type"         => 1,
            "account_type_desc"    => __('coin-type.funding'),
            "recharge_finish_time" => "10",
            "can_withdraw_time"    => "12",
            "contract_ address"    => ""
        ];

        return $data;
    }

    /**
     * @notes 获取已有货币可提币
     * @param int $user_id
     * @param string $search
     * @return bool|array
     * @author Evil丿
     * @date 2025/04/23 09:56
     */
    public static function getUserCoins(int $user_id, string $search = "") : bool|array {
        $addresses = SwtTradeAddress::where('user_id', $user_id)
            -> where('type',1)
            -> where('chain_name', '<>', 'SWT')
            -> distinct()
            -> get();

        if(!$addresses) {
            self::$error = __('coin-type.address_not_found');
            return false;
        }

        $list = [];

        $where = [];

        if($search) {
            $where[] = ["base_ccy",'like','%'.$search.'%'];
        }

        foreach($addresses as $address) {
            $info = SwtMarketChains::where($where)
                -> where('base_ccy', $address -> chain_name)
                -> where('quote_ccy','USD')
                -> select('id','base_ccy','icon','status','full_name')
                -> first()
                -> toArray();

            $info['icon'] = config('app.url').'/storage'.$info['icon'];
            $info['total'] = $address -> total;

            $list[] = $info;
        }

        return $list;
    }
}
